<template>
    <div>
        <div class="zuidaBox">
            <div class="box">
                <div class="flex align_center" style="margin-bottom: 1.5%;padding-left: 24px;">
                    <div class="flex align_center" style="margin-right: 40px;">
                        <div>付款人：</div>
                        <a-select v-model="objcetData.pay_dept_id" style="width:390px;" :filter-option="filterOption"
                            :options="dept_list" :field-names="{ value: 'id', label: 'name' }" allow-clear allow-search
                            placeholder="请选择公司" @change="handleSelectPay_dept_id($event)" />
                    </div>
                </div>
                <a-table :columns="tablecolumnsts" :data="objcetData.detail" :pagination='false'
                    :span-method="spanMethodAll" :bordered="{ wrapper: true, cell: true }">
                    <template #price_type="{ record, rowIndex }">
                        <div v-if="record.type == 1">
                            <a-select v-model="record.price_type" style="flex:1" :filter-option="filterOption"
                                :options="price_typeList" :field-names="{ value: 'key', label: 'title' }" allow-clear
                                allow-search placeholder="计费类型" @change="handleSelect($event, rowIndex)" />
                        </div>
                        <div v-if="record.type == 2">
                            <a-link @click="handleAdd(rowIndex, 1)"><icon-plus /> 添加费用项</a-link>
                        </div>
                    </template>
                    <template #no_tax_price="{ record }">
                        <div v-if="record.price_type && record.pay_real_price">{{ (record.no_tax_price - 0).toFixed(2)
                            }}</div>
                        <div v-else></div>
                    </template>
                    <template #tax_price="{ record }">
                        <div v-if="record.price_type && record.pay_real_price">{{ (record.tax_price - 0).toFixed(2) }}
                        </div>
                        <div v-else></div>
                    </template>
                    <template #pay_name="{ record }">
                        <div v-if="record.type == 1">
                            <a-input v-model="record.pay_name" placeholder="项目名称" allow-clear />
                        </div>
                    </template>
                    <template #pay_price="{ record }">
                        <div v-if="record.type == 1">
                            <a-input v-model="record.pay_price" placeholder="原金额" allow-clear />
                        </div>
                    </template>
                    <template #pay_real_price="{ record, rowIndex }">
                        <div v-if="record.type == 1">
                            <a-input v-model="record.pay_real_price" placeholder="实际金额" allow-clear
                                @input="handleInput($event, rowIndex)" />
                        </div>
                    </template>
                    <template #remark="{ record }">
                        <div v-if="record.type == 1">
                            <a-input v-model="record.remark" placeholder="备注" allow-clear />
                        </div>
                    </template>
                    <template #caozuo="{ record, rowIndex }">
                        <div v-if="record.type == 1">
                            <a-link @click="handleAdd(rowIndex, 2)">删除</a-link>
                        </div>
                    </template>

                </a-table>
            </div>
        </div>
        <div class=" flex align_center" style="padding: 10px 0 0;border-top: 1px solid rgba(0, 0, 0, .15);">
            <div class="flex flex_1 ">
                <!-- <div>不含税合计金额：{{handleZongPrice(3)}}</div>
                <div>税额合计金额：{{handleZongPrice(4)}}</div> -->
                <div>实际支付合计金额：{{ handleZongPrice(2) }}</div>
            </div>
            <!-- <div class="flex" >
                <a-button style="margin-right: 20px;" @click="handleCel">取消支付</a-button>
                <a-popconfirm @ok="handleZhifu" content="是否确认选中的账单收费?确认后将生成一笔待支付账单">
                    <a-button type="primary" >确定选择</a-button>
                </a-popconfirm>
            </div> -->
        </div>

        <a-modal :mask-closable="false" v-model:visible="zhifuShow" title="支付" @cancel="quxiaozhifu" :width="600"
            :on-before-ok="handelzhifuOk">
            <div class="" style="margin-bottom: 2%;padding-left: 24px;height: 300px;">
                <div class="flex align_center" style="margin-bottom: 2%;">
                    <div style="width: 80px;">结算方式：</div>
                    <a-radio-group v-model="jiesuan" :options="jiesuanOptions" />
                </div>
                <div v-if='jiesuan == "3"'>
                    <div style="display: flex;align-items: center;margin-bottom: 2%;">
                        <div style="width: 80px;">支付方式</div>
                        <a-radio-group v-model="zhifu" :options="zhifuOptions" />
                    </div>
                </div>
                <div v-if="jiesuan == '1'" style="margin-bottom: 2%;">
                    <div style="margin-bottom: 2%;">实际付款金额：{{ ((handleZongPrice(2) - 0) *
                        zhifuData.prediction_id.length).toFixed(2)}}元</div>
                    <div>当前可用余额：{{ availableAmount }}元</div>
                </div>
                <div style="display: flex;align-items: center;margin-bottom: 2%;">
                    <div style="width: 80px;">支付时间</div>
                    <a-date-picker style="width: 100%; " show-time v-model="pay_date" format="YYYY-MM-DD HH:mm:ss" />
                </div>
            </div>
        </a-modal>
    </div>
</template>

<script setup>
import { defineProps, defineEmits, ref, reactive, onMounted, watch } from "vue";
import FinancialPayOrder from "@/api/financial/financialPayOrder";
import { request } from "@/utils/request.js";
import commonApi from "@/api/common";
import tool from '@/utils/tool'
import { pinyin } from "pinyin-pro"
import { Message } from "@arco-design/web-vue";
const emit = defineEmits(['quxiao', 'shuaxin', 'price'])
const props = defineProps({
    id: Array,
    dept_id: Number,
    type: Number,   //   type = 1 提货  type = 2 到货  type = 3 装车单
})
const pay_date = ref(tool.dateFormat(
    Math.round(new Date().getTime() / 1000).toString(),
    "yyyy-MM-dd hh:mm:ss"
))
const zongPrice = ref(0)
const itemData = ref({
    page: 1,
    pageSize: 100,
    is_confirm: 0,
})
const zhifu = ref('3')
const jiesuan = ref('')
const opening_bank = ref()
const account = ref()
const account_name = ref()
const fileList = ref('')
const zhifuOptions = ref([
    { label: '对公转账', value: '3' },
    { label: '现金', value: '2' },
    { label: '惠支付', value: '1' },
])
const dept_list = ref([])
const itemList = ref([])
const price_typeList = ref([])    // 计费类型
const zhifuShow = ref(false)
const payOrderId = ref([])
const record_id = ref("")
const zhifuData = ref({
    prediction_id: '',
    pay_dept_id: '',
    pay_items_json: [],
})
const objcetData = ref({
    prediction_id: '',
    pay_dept_id: '',
    detail: [
        {
            type: 1,
            price_type: '',
            pay_name: '',
            no_tax_price: '',
            tax_price: '',
            pay_real_price: '',
            remark: '',
            caozuo: '',
        }, {
            type: 2,
            price_type: '',
            pay_name: '',
            no_tax_price: '',
            tax_price: '',
            pay_real_price: '',
            remark: '',
            caozuo: '',
        }
    ]
})
const shuilvList = ref([])
const filterOption = (v, option) => {
    return option.keywords.some(keywords => keywords.includes(v))
}
const jiesuanOptions = ref([
    {
        label: "现结",
        value: "3",
    },
    {
        label: "周期结算",
        value: "2",
    },
    {
        label: "预付款",
        value: "1",
    }
])

const tablecolumnsts = [

    {
        title: '计费类型',
        dataIndex: 'price_type',
        width: 160,
        slotName: 'price_type'
    },
    {
        title: '收费项目',
        dataIndex: 'pay_name',
        width: 140,
        slotName: 'pay_name'
    },
    {
        title: '实际金额',
        dataIndex: 'pay_real_price',
        width: 120,
        slotName: 'pay_real_price'
    },
    {
        title: '备注',
        dataIndex: 'remark',
        width: 140,
        slotName: 'remark'
    },
    {
        title: '操作',
        dataIndex: 'caozuo',
        slotName: 'caozuo',
        width: 80,
    },
];
const handleSelect = (e, indexs) => {
    console.log(e, indexs)
    let name = ''
    price_typeList.value.map((v, i) => {
        if (v.key == e) {
            name = v.title
        }
    })
    objcetData.value.detail[indexs].pay_name = name
    if (objcetData.value.detail[indexs].pay_real_price != '') {
        gethandleShuilv(indexs)
    }
}
const handleInput = (e, indexs) => {
    if (objcetData.value.detail[indexs].price_type != '') {
        gethandleShuilv(indexs)
    }
}
const availableAmount = ref(0)
watch(
    () => [props.id, props.dept_id],
    ([newProp1, newProp2], [oldProp1, oldProp2]) => {
        console.log('new values:', newProp1, newProp2)
        console.log('old values:', oldProp1, oldProp2)
        zhifuData.value.prediction_id = newProp1
        objcetData.value.prediction_id = newProp1
        objcetData.value.pay_dept_id = newProp2
        if (newProp2 != oldProp2) {
            handelavailableAmount(objcetData.value.pay_dept_id)
        }
    }
)



onMounted(() => {

    handleDeptList()
    commonApi.getDict("price_type").then((res) => {
        res.data.map((v, i) => {
            v.keywords = [
                v.title,
                pinyin(v.title, { toneType: 'none', pattern: 'first' }).split(' ').join(''),
                pinyin(v.title, { toneType: 'none', pattern: 'first' }).split(' ').join('').toUpperCase()
            ]
        })
        price_typeList.value = res.data;
    });
})

const gethandleShuilv = (indexs) => {
    request({
        url: "financial/payOrder/get_tax_price",
        method: "post",
        data: {
            price_type: objcetData.value.detail[indexs].price_type,
            price: objcetData.value.detail[indexs].pay_real_price,
        },
    }).then((res) => {
        console.log(res)
        objcetData.value.detail[indexs].no_tax_price = res.data.no_tax_price
        objcetData.value.detail[indexs].tax_price = res.data.tax_price
    });
}
const getaccount = () => {
    request({
        url: "system/dataDict/index",
        method: "get",
        params: {
            page: 1,
            pageSize: 10,
            type_id: 41
        },
    }).then((res) => {
        opening_bank.value = res.data.items[0].value
        account.value = res.data.items[1].value
        account_name.value = res.data.items[2].value
    });
}
const handleConsole = () => {
    console.log(itemList.value)
}
const handleCel = () => {  // 取消支付
    emit('quxiao')
}
const quxiaozhifu = () => {
    zhifuShow.value = false
    emit('quxiao')
}
const handleZhifu = () => {
    let arr = []
    let err = 0    //  错误提示   1 没有选择付款人  2 实际金额为空或为负数  3 计费类型  4 收费项目  5 原金额  6 请选择账单
    objcetData.value.detail.map((vv, ii) => {
        if ((vv.type == 0) && vv.is_confirm == 1) {
            if (vv.pay_real_price == '' || (vv.pay_real_price - 0) < 0) {
                err = 2
            }
        }
        if (vv.type == 1) {
            if (vv.price_type != '' || vv.pay_name != '' || vv.pay_real_price != '') {
                if (vv.price_type == '') {
                    err = 3
                }
                if (vv.pay_name == '') {
                    err = 4
                }
                if (vv.pay_real_price == '' || (vv.pay_real_price - 0) < 0) {
                    err = 2
                }
            }
        }
    })
    if (err == 2) {
        return Message.error('实际金额不能为空或为负数')
    } else if (err == 3) {
        return Message.error('请选择计费类型')
    } else if (err == 4) {
        return Message.error('请输入收费项目')
    } else {
        objcetData.value.detail.map((v, i) => {
            if (v.type == 1) {
                arr.push(v)
            }
        })
    }
    arr.map((v, i) => {
        v.pay_price = v.pay_real_price
    })
    zhifuData.value.pay_dept_id = objcetData.value.pay_dept_id
    console.log("objcetData:", (handleZongPrice(2) - 0))
    console.log("objcetData:", zhifuData.value.prediction_id.length)
    zhifuData.value.total = ((handleZongPrice(2) - 0) * zhifuData.value.prediction_id.length).toFixed(2)
    zhifuData.value.pay_items_json = arr
    console.log("zhifuData:", zhifuData.value)
    request({
        url: 'financial/payOrder/saveAll',
        method: 'post',
        data: zhifuData.value
    }).then(res => {
        zhifuShow.value = true
        payOrderId.value = res.data.ids
        record_id.value = res.data.record_id
        getaccount()
        console.log('res:', res)
    })
}
const handelzhifuOk = async () => { // 支付成功
    let obj = {}
    let ids = []
    obj.record_id = record_id.value
    itemList.value.map((v, i) => {
        if (v.is_confirm == 1) {
            ids.push(v.id)
        }
    })
    if (jiesuan.value == '1' || jiesuan.value == '2') {
        obj.pay_type = jiesuan.value == 1 ? 'money' : 'periodic'
        obj.ids = payOrderId.value
        obj.pay_date = pay_date.value
    }
    if (jiesuan.value == '3') {
        obj.pay_type = 'now_pay'
        obj.ids = payOrderId.value
        obj.now_pay_type = zhifu.value
        obj.transfer_proof_images = fileList.value
        obj.payment_method = zhifu.value
        obj.settlement_method = 1
        obj.pay_date = pay_date.value
        obj.notes = ''
        // obj.pay_order_id = this.zhifu_id    // 交易单号
        obj.dept_id = zhifuData.value.pay_dept_id    // 公司
        obj.opening_bank = opening_bank.value    // 开户行
        obj.account = account.value    // 收款账户
        obj.account_name = account_name.value    // 开户行名称
    }
    let res = await request({
        // url: "financial/payOrder/pay",
        url: "financial/payOrder/payBatch",
        method: "post",
        data: obj,
    })
    if (res.code == 200) {
        emit("shuaxin")
        Message.success(res.message);
        return true
    } else {
        Message.error(res.message)
        return false
    }

}
const handleSelectPay_dept_id = (e) => {
    objcetData.value.pay_dept_id = e
    handelavailableAmount(e)
}
const handelavailableAmount = (dept_id) => {
    request({
        url: "financial/payOrder/deptList",
        method: "get",
        params: {
            page: 1,
            pageSize: 10,
            id: dept_id
        },
    }).then(resx => {
        availableAmount.value = resx.data.items[0].money
    })
}
const handlechek = (index, rowIndex) => {
    itemList.value[index].detail[rowIndex].is_confirm == 0 ? itemList.value[index].detail[rowIndex].is_confirm = 1 : itemList.value[index].detail[rowIndex].is_confirm = 0
}
const spanMethodAll = ({ record, rowIndex, columnIndex }) => {
    if (rowIndex === record.weizhi - record.weizhizong && columnIndex === 0) {
        return { rowspan: record.weizhizong, colspan: 1 }
    }
};
const handleDeptList = () => {   //  获取公司列表
    request({
        url: 'system/dept/remote',
        method: 'post',
        data: {
            openPage: false,
            remoteOption: {
                filter: {
                    type: ['=', 2],
                    status: ['=', 1]
                },
                select: ["id", "name"],
                sort: { id: "desc" }
            }
        }
    }).then(res => {
        res.data.map((v, i) => {
            v.keywords = [
                v.name,
                pinyin(v.name, { toneType: 'none', pattern: 'first' }).split(' ').join(''),
                pinyin(v.name, { toneType: 'none', pattern: 'first' }).split(' ').join('').toUpperCase()
            ]
        })
        dept_list.value = res.data
    })
}
const handleAdd = (rowIndex, type) => {
    if (type == 1) {  // 新增
        objcetData.value.detail.splice(rowIndex, 0, { price_type: '', pay_name: '', pay_real_price: '', no_tax_price: '', tax_price: '', remark: '', type: 1, caozuo: '' })
    } else {  // 删除
        objcetData.value.detail.splice(rowIndex, 1)
    }



}
const handleZongPrice = (status) => {
    let num = 0
    objcetData.value.detail.map((vv, ii) => {
        if (vv.type == 1 && status == 1) {
            if (vv.pay_price == '') {
                num += 0
            } else {
                num += (vv.pay_price - 0)
            }

        }
        if (vv.type == 1 && status == 2) {
            if (vv.pay_real_price == '') {
                num += 0
            } else {
                num += (vv.pay_real_price - 0)
            }
        }
        if (vv.type == 1 && status == 3) {
            if (vv.no_tax_price == '') {
                num += 0
            } else {
                num += (vv.no_tax_price - 0)
            }
        }
        if (vv.type == 1 && status == 4) {
            if (vv.tax_price == '') {
                num += 0
            } else {
                num += (vv.tax_price - 0)
            }
        }
    })
    emit("price", num.toFixed(2))
    return num.toFixed(2)
}
defineExpose({
    handleZhifu
})
</script>

<style lang="less" scoped>
.zuidaBox {
    max-height: 700px;
    overflow: auto;
    scrollbar-width: none;
}

.zuidaBox::-webkit-scrollbar {
    display: none;
    /* 对于 Chrome, Safari 和 Opera */
}

.box {

    margin-bottom: 20px;

    &:last-child {
        margin-bottom: 0;
    }
}

.chek {
    width: 14px;
    height: 14px;
    border-radius: 2px;
    border: 1px solid rgba(0, 0, 0, .15);
}

.act_chek {
    width: 14px;
    height: 14px;
    border-radius: 2px;
    border: 1px solid rgb(22, 93, 255);
    background: rgb(22, 93, 255);
}
</style>